<template>
  <div class="achievement-container">
    <div class="dashboard-container">
      <div class="dashboard">
        <div class="chart-card">
          <h3 class="chart-title">师生互动情况</h3>
          <div class="chart-wrapper">
            <v-chart
                ref="interactionChartRef"
                :option="interactionChartOptions"
                autoresize
            />
          </div>
        </div>

        <div class="chart-card">
          <h3 class="chart-title">教学内容清晰度</h3>
          <div class="chart-wrapper">
            <v-chart
                ref="contentClarityChartRef"
                :option="contentClarityChartOptions"
                autoresize
            />
          </div>
        </div>

        <div class="ai-card">
          <h3 class="ai-title">AI数据分析</h3>
          <div class="ai-content" v-html="formattedAiMessage"></div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import axios from 'axios'

// 图表配置
const interactionChartOptions = ref({
  backgroundColor: 'transparent'
})
const contentClarityChartOptions = ref({
  backgroundColor: 'transparent'
})
const aiMessage = ref("正在获取分析数据...")

// 格式化AI消息
const formattedAiMessage = computed(() => {
  if (!aiMessage.value) return '';
  // 安全处理HTML转义
  const safeHtml = aiMessage.value
      .replace(/&/g, "&amp;")
      .replace(/</g, "&lt;")
      .replace(/>/g, "&gt;")
      .replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>')
      .replace(/\n/g, '<br>');
  return safeHtml;
});

// 数据获取和处理方法（保持不变）
const fetchChartData = async () => {
  try {
    const response = await axios.post('http://47.113.195.131:8122/api/PatrolClassEvaluation/chartData')
    return response.data.data
  } catch (error) {
    console.error('图表数据加载失败:', error)
    throw error
  }
}

const fetchAnalysisData = async (payload) => {
  try {
    const response = await axios.post(
        'http://47.113.195.131:8122/api/PatrolClassEvaluation/analyzePatrolClass',
        payload
    )
    return response.data
  } catch (error) {
    console.error('分析数据加载失败:', error)
    throw error
  }
}

const processData = async () => {
  try {
    const chartData = await fetchChartData()

    const analysisPayload = {
      interactionStats: chartData.interactionStats.map(item => ({
        count: item.count,
        interactionStatus: item.interaction_status
      })),
      contentClarityStats: chartData.contentClarityStats.map(item => ({
        contentClarity: item.content_clarity,
        count: item.count
      }))
    }

    const [_, analysisResult] = await Promise.all([
      renderCharts(chartData),
      fetchAnalysisData(analysisPayload)
    ])

    // 修正消息赋值逻辑
    aiMessage.value = analysisResult.data || analysisResult.message || "**提示**<br>暂无分析结果"

  } catch (error) {
    aiMessage.value = "**错误**<br>数据加载失败，请检查网络或稍后重试"
    interactionChartOptions.value.title.text = '数据加载失败'
    contentClarityChartOptions.value.title.text = '数据加载失败'
  }
}

const renderCharts = (data) => {
  // 师生互动图表（饼图）
  interactionChartOptions.value = {
    title: { show: false },
    tooltip: {
      trigger: 'item',
      formatter: '{b}: {c} ({d}%)',
      textStyle: { fontSize: 12 }
    },
    legend: {
      bottom: 0,
      left: 'center',
      textStyle: { color: '#333' }
    },
    series: [{
      name: '互动情况',
      type: 'pie',
      radius: ['40%', '70%'],
      avoidLabelOverlap: true,
      itemStyle: {
        borderRadius: 10,
        borderColor: '#fff',
        borderWidth: 2
      },
      label: {
        show: true,
        formatter: '{b}: {c}',
        fontSize: 10
      },
      emphasis: {
        label: {
          show: true,
          fontSize: 12,
          fontWeight: 'bold'
        }
      },
      data: data.interactionStats.map(item => ({
        value: item.count,
        name: getInteractionStatus(item.interaction_status),
        itemStyle: {
          color: getInteractionColor(item.interaction_status)
        }
      }))
    }]
  }

  // 教学内容清晰度（柱状图）
  contentClarityChartOptions.value = {
    title: { show: false },
    tooltip: {
      trigger: 'axis',
      axisPointer: { type: 'shadow' },
      textStyle: { fontSize: 12 }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '15%',
      top: '15%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      axisLabel: {
        fontSize: 10,
        interval: 0,
        rotate: 30
      },
      data: data.contentClarityStats.map(item => getClarityText(item.content_clarity))
    },
    yAxis: {
      type: 'value',
      axisLabel: { fontSize: 10 }
    },
    series: [{
      name: '数量',
      type: 'bar',
      barWidth: '60%',
      itemStyle: {
        color: function(params) {
          const colors = ['#FF6B81', '#FFA07A', '#98FB98'];
          return colors[params.dataIndex % colors.length]
        }
      },
      data: data.contentClarityStats.map(item => item.count)
    }]
  }
}

// 辅助函数
const getInteractionStatus = (status) => {
  switch (status) {
    case 1: return '较差';
    case 2: return '一般';
    case 3: return '良好';
    default: return `状态${status}`;
  }
}

const getInteractionColor = (status) => {
  switch (status) {
    case 1: return '#f5222d'; // 较差-红色
    case 2: return '#faad14'; // 一般-橙色
    case 3: return '#52c41a'; // 良好-绿色
    default: return '#d9d9d9';
  }
}

const getClarityText = (clarity) => {
  switch (clarity) {
    case 1: return '不清晰';
    case 2: return '较清晰';
    case 3: return '清晰';
    default: return `清晰度${clarity}`;
  }
}

onMounted(() => {
  processData()
})
</script>

<style scoped>
.achievement-container {
  height: 100vh; /* 根据需要设置固定高度 */
  overflow-y: auto; /* 允许垂直滚动 */
  padding: 10px; /* 内边距 */
}
.dashboard-container {
  padding: 12px;
  background-color: #f7f8fa;
  min-height: 100vh;
}

.dashboard {
  display: flex;
  flex-direction: column;
  gap: 16px;
  max-width: 600px;
  margin: 0 auto;
}

.chart-card, .ai-card {
  background: white;
  border-radius: 12px;
  padding: 16px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.chart-title, .ai-title {
  margin: 0 0 12px 0;
  font-size: 16px;
  font-weight: 500;
  color: #333;
  text-align: center;
}

.chart-wrapper {
  width: 100%;
  height: 280px;
}

.ai-content {
  font-size: 14px;
  line-height: 1.8;
  color: #666;
}

.ai-content strong {
  font-weight: bold;
  color: #1890ff;
}

/* 移动端适配 */
@media (max-width: 480px) {
  .chart-card, .ai-card {
    padding: 12px;
  }

  .chart-wrapper {
    height: 240px;
  }

  .chart-title, .ai-title {
    font-size: 15px;
  }

  .ai-content {
    font-size: 13px;
  }
}
</style>